package utils

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/md5"
	"encoding/base64"
	"encoding/json"
	"fmt"
)

func MD5(data string) string {
	hash := md5.New()
	hash.Write([]byte(data))
	return fmt.Sprintf("%x", hash.Sum(nil))
}

func MD5Interface(data interface{}) string {
	dataByte, _ := json.Marshal(data)
	hash := md5.New()
	hash.Write([]byte(dataByte))
	return fmt.Sprintf("%x", hash.Sum(nil))
}

// 对称加密
func Encrypt(data interface{}, secret string) (dest string) {
	dataByte, err := json.Marshal(data)
	if err != nil {
		Error(err)
		return
	}
	var cryptedBytes []byte
	cryptedBytes, err = aesEncrypt(dataByte, []byte(secret))
	if err != nil {
		Error(err)
		return
	}
	return base64.RawURLEncoding.EncodeToString(cryptedBytes)
}

// 对称解密
func Decrypt(dest, secret string, res interface{}) (err error) {
	decoded, err := base64.RawURLEncoding.DecodeString(dest)
	if err != nil {
		return
	}
	data, err := aesDecrypt(decoded, []byte(secret))
	if err != nil {
		return
	}
	err = json.Unmarshal(data, res)
	return
}

func aesEncrypt(origData, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	origData = pkcs5Padding(origData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	crypted := make([]byte, len(origData))

	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

func aesDecrypt(crypted, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	origData := make([]byte, len(crypted))
	if len(origData)%blockSize != 0 {
		return nil, fmt.Errorf("input not full blocks")
	}
	blockMode.CryptBlocks(origData, crypted)
	origData = pkcs5UnPadding(origData)
	return origData, nil
}

func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func pkcs5UnPadding(origData []byte) []byte {
	length := len(origData)
	// 去掉最后一个字节 unpadding 次
	unpadding := int(origData[length-1])
	if unpadding > length {
		return nil
	}
	return origData[:(length - unpadding)]
}
